//
//  BCPublishViewController.m
//  BCManagerVersion
//
//  Created by ZhaoXiang on 3/6/14.
//  Copyright (c) 2014 Jungle. All rights reserved.
//

#import "BCPublishViewController.h"
#import "BCPublishUserInfoCell.h"
#import "BCPublishAddressCell.h"
#import "BCPublishProductCell.h"
#import "UIImageView+WebCache.h"
#import "ClientProdutModel.h"
#import "BCMUserSettingViewController.h"
#import "BCMEditProductViewController.h"
#import "BCProgressHUD.h"

#define ADD_PRODUCT_MESSAGE @"点击添加产品"

#define ADD_PRODUCT_TITLE @""

#define MAX_PRODUCTS 5

@interface BCPublishViewController ()<UITableViewDataSource,
UITableViewDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIActionSheetDelegate>

@property(nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic, strong) BCMEditProductViewController* editProductVC;
@property (nonatomic, strong) NSArray* icons;
@end

@implementation BCPublishViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.tableView registerClass:[BCPublishUserInfoCell class]
           forCellReuseIdentifier:@"BCPublishUserInfoCell"];
    
    [self.tableView registerClass:[BCPublishAddressCell class]
           forCellReuseIdentifier:@"BCPublishAddressCell"];
    
    [self.tableView registerClass:[BCPublishProductCell class]
           forCellReuseIdentifier:@"BCPublishProductCell"];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    __weak typeof(self)weakSelf = self;
    [BCProgressHUD showWithTile:@"下载中" animated:YES];
    [BCNetworkClient adsInfo:USER_MANAGER.uid type:@"detail" reqFriendUid:@0
                     success:^(NSDictionary *info) {
                         if ([info[@"modified_time"] isEqualToString:USER_MANAGER.modified_time]) {
                             //not updated
                             if ([info[@"verified"] isEqual:[NSNull null]]) {
                                 BCMUserSettingViewController *setting = [[BCMUserSettingViewController alloc]init];
                                 [weakSelf.navigationController pushViewController:setting animated:YES];
                             }
                             else if([info[@"verified"] intValue] == 2) {
                                 [USER_MANAGER configWithModel:info];
                                 [USER_MANAGER save];
                                 [UIAlertView showWithTitle:@"审核被拒绝"
                                                    message:info[@"reason"]
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil tapBlock:nil];
                             } else {
                                 USER_MANAGER.verified = info[@"verified"];
                                 [USER_MANAGER save];
                             }
                         } else {
                             [USER_MANAGER configWithModel:info];
                             [USER_MANAGER save];
                         }
                         
                         [BCNetworkClient product:USER_MANAGER.uid
                                             type:@"list"
                                            start:0
                                            limit:0
                                          success:^(NSNumber *total, NSArray *products) {
                                              
                                              self.dataSource = [NSMutableArray arrayWithArray:[ClientProdutModel modelsWithDataSource:products]];
                                              
                                              while (self.dataSource.count < MAX_PRODUCTS) {
                                                  ClientProdutModel *model =[[ClientProdutModel alloc] init];
                                                  model.title = ADD_PRODUCT_TITLE;
                                                  model.message = ADD_PRODUCT_MESSAGE;
                                                  model.productState = PRODUCT_STATE_ADD;
                                                  [self.dataSource addObject:model];
                                              }
                                              
                                              [BCNetworkClient productIconsSuccess:^(NSArray *icons) {
                                                  self.icons = icons;
                                                  [BCProgressHUD hideAnimated:YES];
                                                  [self.tableView reloadData];
                                                  
                                              } failure:^(NSError *error) {
                                                  [BCProgressHUD hideWithError:error animated:YES];
                                              }];
                                              
                                              
                                          } failure:^(NSError *error) {
                                              [BCProgressHUD hideWithError:error animated:YES];
                                              
                                          }];
                         
                     }
                     failure:^(NSError *error) {
                         [BCProgressHUD hideWithError:error animated:YES];
                     }
     ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 3;
    } else {
        return 5;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 121;
    } else if(indexPath.section == 1) {
        return 32;
    } else {
        return 47;
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView* header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 5)];
    header.backgroundColor = [UIColor colorWithRed:227.0f/0xFF green:227.0f/0xFF blue:227.0f/0xFF alpha:1.0f];
    return header;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BCPublishUserInfoCell"
                                               forIndexPath:indexPath];
        [self configUserInfoCell:(BCPublishUserInfoCell*)cell];
    } else if(indexPath.section == 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BCPublishAddressCell"
                                               forIndexPath:indexPath];
        [self configAddressCell:(BCPublishAddressCell*)cell atIndexPath:indexPath];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BCPublishProductCell"
                                               forIndexPath:indexPath];
        [self configProductCell:(BCPublishProductCell*)cell atIndexPath:indexPath];
    }
    
    return cell;
}

- (void)configUserInfoCell:(BCPublishUserInfoCell*)cell
{
    if (USER_MANAGER.name == nil || USER_MANAGER.name.length == 0) {
        return;
    }
    [cell.avatar setImageWithURL:[NSURL URLWithString:USER_MANAGER.avatar]
                placeholderImage:[UIImage imageNamed:@"ManagerAvatar_placeholder.png"]];
    
    cell.avatar.userInteractionEnabled = YES;
    [cell.avatar addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(updateAvatar:)]];
    
    cell.name.text = USER_MANAGER.name;
    cell.gender.text = @[@"男", @"女"][USER_MANAGER.gender.intValue];
    cell.workTime.text = USER_MANAGER.workTimeString;
    cell.workType.text = USER_MANAGER.workTypeString;
    cell.age.text = USER_MANAGER.age;
}

- (void)configAddressCell:(BCPublishAddressCell*)cell atIndexPath:(NSIndexPath *)indexPath
{
    if (USER_MANAGER.name == nil || USER_MANAGER.name.length == 0) {
        return;
    }
    NSUInteger row = indexPath.row;
    cell.icon.image = [UIImage imageNamed:@[@"address.png", @"map.png", @"phone.png"][row]];
    if (row == 0) {
        cell.text.text = [NSString stringWithFormat:@"%@-%@-%@",
                          USER_MANAGER.bankMain, USER_MANAGER.bankSub1, USER_MANAGER.bankSub2];
    } else if (row == 1) {
        cell.text.text = USER_MANAGER.address;
    } else if (row == 2) {
        cell.text.text = USER_MANAGER.tel;
    }
}

- (void)configProductCell:(BCPublishProductCell*)cell atIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataSource == nil || self.dataSource.count <= indexPath.row) {
        return;
    }
    NSUInteger row = indexPath.row;
    ClientProdutModel* model = self.dataSource[row];
    [cell.icon setImageWithURL:[NSURL URLWithString:model.image]];
    cell.message.text = model.message;
    cell.title.text = model.title;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 || indexPath.section == 1) {
        //edit user info
        BCMUserSettingViewController* newVC = [[BCMUserSettingViewController alloc] init];
        [self.navigationController pushViewController:newVC animated:YES];
    } else if (indexPath.section == 2) {
        //edit or add product
        self.editProductVC = [[BCMEditProductViewController alloc] initWithProduct:self.dataSource[indexPath.row]
                                                                           success:^{
                                                                               [self.editProductVC.view removeFromSuperview];
                                                                               self.editProductVC = nil;
                                                                               [self.tableView reloadData];
                                                                           } cancel:^{
                                                                               [self.editProductVC.view removeFromSuperview];
                                                                               self.editProductVC = nil;
                                                                           }];
        self.editProductVC.product = self.dataSource[indexPath.row];
        self.editProductVC.icons = self.icons;
        [self.view addSubview:self.editProductVC.view];
        
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        ClientProdutModel* product = self.dataSource[indexPath.row];
        
        return product.productState == PRODUCT_STATE_NORMAL;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [BCProgressHUD showWithTile:@"删除中" animated:YES];
        [BCNetworkClient removeProduct:USER_MANAGER.auth
                                  type:@"remove"
                             productId:[self.dataSource[indexPath.row] id]
                               success:^{
                                   [BCProgressHUD hideAnimated:YES];
                                   [self.dataSource removeObjectAtIndex:indexPath.row];
                                   ClientProdutModel *model =[[ClientProdutModel alloc] init];
                                   model.title = ADD_PRODUCT_TITLE;
                                   model.message = ADD_PRODUCT_MESSAGE;
                                   model.productState = PRODUCT_STATE_ADD;
                                   [self.dataSource addObject:model];
                                   [self.tableView reloadData];
                                   
                               } failure:^(NSError *error) {
                                   [BCProgressHUD hideWithError:error animated:YES];
                               }];
    }
}

-(void)updateAvatar:(UIImageView *)sender
{
    //take the photo
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"相册", nil];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    if (buttonIndex == actionSheet.destructiveButtonIndex) {
        //take photo
        sourceType = UIImagePickerControllerSourceTypeCamera;
    } else if (buttonIndex == actionSheet.firstOtherButtonIndex) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        return;
    }
    
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    
    picker.allowsEditing = YES;
    
    picker.sourceType = sourceType;
    
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

extern const CFStringRef kUTTypeImage;

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
        == kCFCompareEqualTo) {
        
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }
        
        NSData* dateToUpload = UIImageJPEGRepresentation(imageToSave, 0.5f);
        
        [BCProgressHUD showWithTile:@"正在上传头像" animated:YES];
        
        [BCNetworkClient uploadAvatar:USER_MANAGER.auth
                            imageData:dateToUpload
                              success:^(NSString *avatarUrl, NSString *tAvatar) {
                                  
                                  [BCProgressHUD hideAnimated:YES];
                                  [self dismissViewControllerAnimated:YES completion:^{
                                      //reload avatar
                                      USER_MANAGER.avatar = avatarUrl;
                                      [USER_MANAGER save];
                                      [self.tableView reloadData];
                                  }];
                                  
                              } failure:^(NSError *error) {
                                  [BCProgressHUD hideWithError:error animated:YES];
                                 
                              }];
    } else {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
    
}
@end
